import numpy as np

cheek_outline_index = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32]
nose_bridge_index = [101, 103, 102, 100]
nose_arc = [97, 95, 94, 93, 91]
mouth_outline = [71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82]
mouth_inline = [83, 84, 85, 86, 87, 88]
# eye_left = [53, 54, 55, 57, 58, 51]
# eye_right = [61, 62, 63, 65, 66, 59]
# eyebrow_left = [34, 35, 36, 37, 38, ]
# eyebrow_right = [43, 44, 45, 46, 47, ]


total_index = cheek_outline_index + nose_bridge_index + nose_arc + mouth_outline + mouth_inline


def get_point_between(point1, point2, ratio=0.5):

    x1, y1 = point1
    x2, y2 = point2
    
    # 使用线性插值计算两点之间的点
    x = x1 + ratio * (x2 - x1)
    y = y1 + ratio * (y2 - y1)
    
    return (x, y)

def get_center_of_three_points(point1, point2, point3):
    x1, y1 = point1
    x2, y2 = point2
    x3, y3 = point3
    
    # 计算三个点的中心点（质心）
    x = (x1 + x2 + x3) / 3
    y = (y1 + y2 + y3) / 3
    
    return (x, y)

def convert_to_68_landmarks(landmarks):
    landmarks_68 = [landmarks[i] for i in total_index]
    # 特殊点位
    left_eye_1 = get_point_between(landmarks[53], landmarks[54], 0.5)
    left_eye_2 = get_point_between(landmarks[53], landmarks[52], 0.5)
    left_eye_3 = get_point_between(landmarks[57], landmarks[56], 0.5)
    left_eye = [landmarks[55], left_eye_1, left_eye_2, landmarks[51], landmarks[58], left_eye_3]
    landmarks_68.extend(left_eye)
    
    right_eye_1 = get_point_between(landmarks[61], landmarks[62], 0.5)
    right_eye_2 = get_point_between(landmarks[61], landmarks[60], 0.5)
    right_eye_3 = get_point_between(landmarks[65], landmarks[64], 0.5)
    right_eye = [landmarks[63], right_eye_1, right_eye_2, landmarks[59], landmarks[66], right_eye_3]
    landmarks_68.extend(right_eye)

    eyebrow_left_1 = get_point_between(landmarks[34], landmarks[41], 0.5)
    eyebrow_left_2 = get_center_of_three_points(landmarks[35], landmarks[36], landmarks[40])
    eyebrow_left_3 = get_point_between(landmarks[37], landmarks[39], 0.5)
    eyebrow_left = [landmarks[33], eyebrow_left_1, eyebrow_left_2, eyebrow_left_3, landmarks[38],]
    landmarks_68.extend(eyebrow_left)

    eyebrow_right_1 = get_point_between(landmarks[43], landmarks[50], 0.5)
    eyebrow_right_2 = get_center_of_three_points(landmarks[44], landmarks[45], landmarks[49])
    eyebrow_right_3 = get_point_between(landmarks[46], landmarks[48], 0.5)
    eyebrow_right = [landmarks[42], eyebrow_right_1, eyebrow_right_2, eyebrow_right_3, landmarks[47],]
    landmarks_68.extend(eyebrow_right)
    
    landmarks_68.append(landmarks[104])
    landmarks_68.append(landmarks[105])
    
    landmarks_68 = np.array(landmarks_68)

    return landmarks_68

def trans_dlib_68(landmarks):
    dlib_mapping_path = "landmarks_mapping.npy"
    dlib_mapping = np.load(dlib_mapping_path)
    landmarks_68=convert_to_68_landmarks(landmarks)
    landmarks_dlib_68 = landmarks_68[dlib_mapping]
    return landmarks_dlib_68